import { getSetting, chooseAddress, openSetting, showModal ,showToast} from "../../utils/asyncWx.js";
import regeneratorRuntime from '../../lib/runtime/runtime';
const app = getApp()
Page({
  data: {
    address: {},
    cart: app.globalData.shopCar,
    allChecked: false,
    totalPrice: 0,
    totalNum: 0,
    isAll: false
  },
  count(){
    var that = this
    var totalPrice = 0
    var totalNum = 0
    var cart = that.data.cart
    var c = 0
    cart.forEach(item => {
      if(item.checked == true){
        totalPrice += item.price * item.num
        c++
      }
    });
    totalNum = c
    that.setData({
      cart: cart,
      totalPrice: totalPrice,
      totalNum: totalNum
    })
    app.globalData.shopCar = cart
  },
  checkAll(){
    var that = this
    var cart = that.data.cart
    var isAll = that.data.isAll
    var i = 0
    cart.forEach(item => {
      if(item.checked != true){
        i++
      }
    });
    if(i != 0){
      isAll = false
    }else{
      isAll = true
    }
    that.setData({
      isAll: isAll
    })
  },
  checkedOne(e){
    var that = this
    var index = e.currentTarget.dataset.index
    var cart = that.data.cart
    cart[index].checked = !cart[index].checked
    that.setData({
      cart: cart
    })
    app.globalData.shopCar = cart
    that.checkAll()
    that.count()
  },
  add(e){
    var that = this
    var index = e.currentTarget.dataset.index
    var cart = that.data.cart
    cart[index].num ++
    that.setData({
      cart: cart
    })
    app.globalData.shopCar = cart
    that.count()
  },
  sub(e){
    var that = this
    var index = e.currentTarget.dataset.index
    var cart = that.data.cart
    if(cart[index].num > 1){
      cart[index].num --
    }
    that.setData({
      cart: cart
    })
    app.globalData.shopCar = cart
    that.count()
  },
  checked(){
    var that = this
    var cart = that.data.cart
    var isAll = that.data.isAll
    if(isAll == true){
      isAll = false
      cart.forEach(item => {
        item.checked = false
      });
    }else{
      isAll = true
      cart.forEach(item => {
        item.checked = true
      });
    }
    app.globalData.shopCar = cart
    that.checkAll()
    that.count()
  },
  handlePay(){
    var that = this
    if(that.data.totalNum > 0){
      wx.navigateTo({
        url: '../pay/index',
      })
    }
  },
  onShow() {
    var that = this
    // 1 获取缓存中的收货地址信息
    const address = wx.getStorageSync("address");
    that.setData({
      address,
      cart: app.globalData.shopCar
    })
  },
})